<template>
  <div class="dataset-list-page">
    <!-- 操作区 -->
    <div class="op-bar">
      <el-button type="primary" @click="openEditDialog()">新建数据集</el-button>
      <el-button @click="exportDatasetsExcel">导出数据</el-button>
      <el-upload
        :show-file-list="false"
        accept=".json"
        :before-upload="importDatasets"
      >
      </el-upload>
    </div>
    <!-- 数据集表格 -->
    <el-table :data="datasets" border style="width: 100%; margin-top: 12px">
      <el-table-column prop="name" label="数据集名称" min-width="120" />
      <el-table-column prop="group" label="分组" min-width="90" />
      <el-table-column prop="desc" label="描述" min-width="160" />
      <el-table-column prop="created" label="创建时间" width="110" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="openPreview(scope.row)">预览</el-button>
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteDataset(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建/编辑弹窗 -->
    <el-dialog :title="editingRow ? '编辑数据集' : '新建数据集'" v-model="editDialogVisible" width="420px" @close="resetForm">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-input v-model="form.group" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" v-model="form.desc" />
        </el-form-item>
        <el-form-item label="字段" prop="fields">
          <el-select v-model="form.fields" multiple placeholder="请选择字段" style="width:100%">
            <el-option v-for="item in fieldOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog title="数据集预览" v-model="previewDialogVisible" width="620px">
      <el-table :data="previewData" border height="280">
        <el-table-column v-for="f in previewFields" :key="f" :label="f" :prop="f" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'


// 模拟字段选项
const fieldOptions = [
  '编号', '日期', '客户名称', '产品名称', '数量', '金额', '地区', '负责人', '状态', '备注'
]

// 模拟生成15条合理的数据集
function createMockDatasets() {
  const groups = ['销售', '生产', '库存', '财务', '人力', '市场']
  const descs = [
    '月度销售记录', '订单流水', '原材料采购', '库存盘点', '人事信息',
    '薪资明细', '客户名录', '供应商列表', '设备维护', '合同管理',
    '预算执行', '考勤打卡', '售后反馈', '营销活动', '财务报表'
  ]
  let arr = []
  for (let i = 0; i < 15; i++) {
    arr.push({
      id: i + 1,
      name: descs[i],
      group: groups[i % groups.length],
      desc: descs[i] + '数据集，供分析用',
      created: `2024-07-${String(7 - (i % 7)).padStart(2, '0')}`,
      fields: fieldOptions.slice(0, 3 + (i % 5)),
      data: mockTableData(fieldOptions.slice(0, 3 + (i % 5)))
    })
  }
  return arr
}
// 随机生成表格数据用于预览
function mockTableData(fields) {
  let data = []
  for (let i = 0; i < 5; i++) {
    let row = {}
    for (let f of fields) {
      row[f] = f === '数量' || f === '金额'
        ? Math.floor(Math.random() * 2000) + 1
        : f + (i + 1)
    }
    data.push(row)
  }
  return data
}

const datasets = ref(createMockDatasets())

// 弹窗相关
const editDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const editingRow = ref(null)
const form = reactive({ name: '', group: '', desc: '', fields: [] })
const formRef = ref()
const formRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  group: [{ required: true, message: '请输入分组', trigger: 'blur' }],
  fields: [{ required: true, message: '请选择字段', trigger: 'change' }]
}
const previewFields = ref([])
const previewData = ref([])

// 新建或编辑
function openEditDialog(row = null) {
  if (row) {
    Object.assign(form, row)
    editingRow.value = row
  } else {
    resetForm()
    editingRow.value = null
  }
  editDialogVisible.value = true
}
function resetForm() {
  form.name = ''
  form.group = ''
  form.desc = ''
  form.fields = []
}

// 保存（新建或编辑）
function submitForm() {
  formRef.value.validate((valid) => {
    if (!valid) return
    if (editingRow.value) {
      // 编辑
      Object.assign(editingRow.value, { ...form })
      ElMessage.success('修改成功')
    } else {
      // 新建
      datasets.value.unshift({
        ...form,
        id: Date.now(),
        created: new Date().toISOString().slice(0, 10),
        data: mockTableData(form.fields)
      })
      ElMessage.success('添加成功')
    }
    editDialogVisible.value = false
    resetForm()
  })
}

// 删除
function deleteDataset(row) {
  datasets.value = datasets.value.filter(ds => ds.id !== row.id)
  ElMessage.success('已删除')
}

// 预览
function openPreview(row) {
  previewFields.value = row.fields
  previewData.value = row.data
  previewDialogVisible.value = true
}

// 导出数据集
function exportDatasetsExcel() {
  const excelData = datasets.value.map(ds => ({
    '数据集名称': ds.name,
    '分组': ds.group,
    '描述': ds.desc,
    '创建时间': ds.created,
    '字段': ds.fields.join(', ')
  }))
  const ws = XLSX.utils.json_to_sheet(excelData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '数据集列表')
  XLSX.writeFile(wb, 'datasets.xlsx')
}

</script>

<style scoped>
.dataset-list-page {
  padding: 24px;
}
.op-bar {
  margin-bottom: 12px;
}
</style>
